package org.cheniy.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.cheniy.domain.strategy.model.entity.StrategyRuleEntity;
import org.cheniy.domain.strategy.repository.IStrategyRepository;
import org.cheniy.domain.strategy.service.armory.IStrategyDispatch;
import org.cheniy.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.cheniy.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.cheniy.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author cheniy
 * @description 权重过滤责任链节点
 * @create 2025/3/7 22:24
 */
@Slf4j
@Component("rule_weight")
public class WeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository iStrategyRepository;

    @Resource
    private IStrategyDispatch iStrategyDispatch;

    // TODO 暂时固定用户积分
    // public Long userScore=0L;
    /**
     * 权重规则过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     *
     * @param userId
     * @param strategyId
     * @return 奖品id
     */

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        // 1. 获取规则实体
        StrategyRuleEntity strategyRuleEntity = iStrategyRepository.queryStrategyRule(strategyId, ruleModel());

        // 2. 获取到权重规则字符串，并进行分割创建map中
        String ruleValue = strategyRuleEntity.getRuleValue();
        Map<Long, String> analyticalValueMap = this.getAnalyticalValue(ruleValue);
        if (null == analyticalValueMap || analyticalValueMap.isEmpty()) return next().logic(userId,strategyId);;
        // 3. 将map的key，及积分范围节点，得到list并排序筛选
        ArrayList<Long> keyList = new ArrayList<>(analyticalValueMap.keySet());
        Collections.sort(keyList);

        Integer userScore = iStrategyRepository.queryActivityAccountTotalUseCount(userId, strategyId);

        // 4. 获取到最大小于用户积分的权值积分
        Long nextValue = keyList.stream()
                .filter(key -> userScore >= key)
                .max(Comparator.naturalOrder())
                .orElse(null);


        // 5. nextValue存在则放行到下一个责任链节点，否则权重抽奖返回奖品id
        if (null!=nextValue){
            Integer awardId = iStrategyDispatch.getRandomAwardId(strategyId, analyticalValueMap.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        return next().logic(userId,strategyId);
    }

    @Override
    public String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
    // 分离权重组，分数为key，值字符串为值（4000,“4000:101,102”）
    private Map<Long, String> getAnalyticalValue(String ruleValue){
        String[] ruleWeightValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleWeightValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }


}
